package top.lyc829.days.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.lyc829.days.bean.User;
import top.lyc829.days.service.UserService;
import top.lyc829.days.util.Result;

@RestController    //相当于@Controller+@RequestBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/regist")
    public Result regist(@RequestBody JSONObject jsonParam) {

        String userName=jsonParam.get("userName").toString();
        String password = jsonParam.get("password").toString();

        User user = new User(userName, password);

        System.out.println(userName + "\n" + password + "\n");

        Result result = new Result(null, false, null);

        try {
            User existUser = userService.getUserByUserName(user.getUsername());
            if(existUser != null) {
                //如果用户名已存在
                result.setMsg("用户名已存在");
            }else{
                userService.addUser(user);
                result.setMsg("注册成功");
                result.setSuccess(true);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    // TODO : 这里有个逻辑错误：未注册直接登陆时只提示用户名或密码错误，应该提示用户不存在
    @RequestMapping("/login")
    public Result login(@RequestBody JSONObject jsonParam) {

        String userName=jsonParam.get("userName").toString();
        String password = jsonParam.get("password").toString();

        Result result = new Result(null, false, null);

        try {
            User user = userService.getUserByUserNameAndPassword(userName, password);
            if(user == null){
                result.setMsg("用户名或密码错误");
            }else{
                result.setMsg("登录成功");
                result.setSuccess(true);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }


}
